﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Cryptography;

namespace pc_system.Model
{
    class GlobalVariables
    {
        public static int STORE_ID = 1;
        public static string POS_PORT = "COM2";
        public static int STAFF_ID = 0;
        public static string STAFF_NAME = "无收银员";
        public static bool ADDED_ORDERS = true;
        public static int STAFF_TYPE = 0;
        public static bool ADDED_PRODUCTS = true;
        public static int CLIENT_ID = 0;
        //TODO: 保存系统变量
    }
    class DBFunc
    {
        public static int STOREID = 0;
        private static dbEntities db = new dbEntities();
        private static dbEntities _db;
        private static int CREDIT = 100;    //介绍人获得的积分数
        public static bool validate(string id, string password)
        {
            //using (var db = new dbEntities())
            _db = new dbEntities();
            {
                int wId = -1;
                if (!Int32.TryParse(id, out wId))
                {
                    return false;
                }
                password = SHA256Encrypt(password+"fqm");
                //TODO: 员工类型
                var result = _db.staffs.FirstOrDefault(c => c.staff_id == wId && c.staff_password == password && c.store_id == GlobalVariables.STORE_ID);
                if (result != null)
                {
                    GlobalVariables.STAFF_ID = result.staff_id;
                    GlobalVariables.STAFF_NAME = result.staff_name;
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public static string SHA256Encrypt(string strIN)
        {
            //string strIN = getstrIN(strIN);
            byte[] tmpByte;
            SHA256 sha256 = new SHA256Managed();

            tmpByte = sha256.ComputeHash(Encoding.Default.GetBytes(strIN));
            sha256.Clear();

            return Convert.ToBase64String(tmpByte);

        }
        
        public static vProduct findProduct(string barcode)
        {
            var pd = db.vProduct.FirstOrDefault(c => c.product_code == barcode && c.store_id == STOREID);
            return pd;
        }



        /// <summary>
        /// 添加销售记录
        /// </summary>
        /// <param name="bcode"></param>
        /// <param name="count"></param>
        /// <param name="fPrice"></param>
        /// <param name="saleid"></param>
        /// <returns></returns>
        public static bool commitOrder(string bcode,int count, float fPrice , int saleid)
        {
            _db = new dbEntities();
            vProduct pIF = _db.vProduct.FirstOrDefault(c => c.product_code == bcode);
            //TODO: 库存不足
            if (pIF.total_count < count) return false;
            try
            {
                while (pIF.stock_count < count)
                {
                    product_in_stock pis = _db.product_in_stock.FirstOrDefault(c => c.product_id == pIF.pid && c.stock_count != 0);
                    salehistory_detail shd = new salehistory_detail();
                    shd.order_id = saleid;
                    shd.product_id = pIF.pid;
                    shd.product_inprice = pIF.cost_price;
                    shd.product_count = pIF.stock_count;
                    shd.product_saleprice = (float)pIF.sale_prices;
                    shd.product_discount_price = fPrice;
                    _db.AddTosalehistory_detail(shd);
                    count -= pis.stock_count;
                    _db.DeleteObject(pis);
                    _db.SaveChanges();
                    pIF = _db.vProduct.FirstOrDefault(c => c.product_code == bcode);
                }
                product_in_stock pis2 = db.product_in_stock.FirstOrDefault(c => c.product_id == pIF.pid && c.stock_count != 0);
                if (pis2.stock_count == 0) db.DeleteObject(pis2);
                pis2.stock_count -= count;

                {
                    salehistory_detail shd = new salehistory_detail();
                    shd.order_id = saleid;
                    shd.product_id = pIF.pid;
                    shd.product_inprice = pIF.cost_price;
                    shd.product_count = count;
                    shd.product_saleprice = (float)pIF.sale_prices;
                    shd.product_discount_price = fPrice;
                    db.AddTosalehistory_detail(shd);
                }
                db.SaveChanges();
            }
            catch(Exception)
            {
                return false;
            }
            return true;
        }
        #region 添加会员
        public static bool addClient(string name, DateTime birth, string phone, string intoder, string comment)
        {
            //TODO:会员生日 介绍人处理
            var cl = db.clients.FirstOrDefault(c => c.client_phone == phone);
            var intr = db.clients.FirstOrDefault(c => c.client_name == intoder);
            if (cl != null) return false;

            clients add_cl = new clients();
            add_cl.client_storeid = GlobalVariables.STORE_ID;
            add_cl.client_name = name;
            add_cl.client_phone = phone;
            add_cl.client_joindate = DateTime.Now;
            add_cl.client_type = 1;
            add_cl.client_money = 0;
            add_cl.client_remark = comment;

            //如果有介绍人，则介绍人获得积分
            if (intr != null)
            {
                intr.client_credit += CREDIT;
                add_cl.client_introducer = intr.client_id;
            }
            try
            {
               
                db.AddToclients(add_cl);
                db.SaveChanges();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 退货
        public static bool returnGood(int order_detail_id)
        {
            _db = new dbEntities();
            var rp = _db.salehistory_detail.FirstOrDefault(c => c.detail_id == order_detail_id);
            var ord = _db.salehistory.FirstOrDefault(c => c.order_id == rp.order_id);
            if (ord == null|| rp == null || rp.is_returned == 1) return false;
            var pos = _db.product_in_stock.FirstOrDefault(c => c.product_id == rp.product_id &&
                c.store_id == ord.store_id &&
                c.cost_price == rp.product_inprice);
            if (pos == null)
            {
                pos = product_in_stock.Createproduct_in_stock(rp.product_id, rp.product_count, rp.product_inprice, ord.store_id);
                _db.AddToproduct_in_stock(pos);
            }
            else
            {
                pos.stock_count += rp.product_count;
            }
            rp.is_returned = 1;
            _db.SaveChanges();
            return true;
        }
        #endregion

        #region 添加进货
        public static bool addNewBuyRecord(string bcode, int count, float cPrice)
        {
            _db = new dbEntities();
            var pid = _db.products_info.Where(c => c.product_code == bcode).Select(c => c.product_id).First();
            //TODO: 需要添加事务？
            try
            {
                //添加进货记录
                product_bought_record pbr = new product_bought_record();
                pbr.product_id = pid;
                pbr.cost_price = cPrice;
                pbr.product_count = count;
                pbr.recode_date = DateTime.Now;
                pbr.store_id = GlobalVariables.STORE_ID;
                _db.AddToproduct_bought_record(pbr);
                _db.SaveChanges();
                //添加库存
                product_in_stock pis = db.product_in_stock.FirstOrDefault(c => c.product_id == pid && c.cost_price == cPrice);
                if (pis != null)
                {
                    pis.stock_count += count;
                }
                else
                {
                    pis = new product_in_stock();
                    pis.product_id = pid;
                    pis.cost_price = cPrice;
                    pis.stock_count = count;
                    pis.store_id = GlobalVariables.STORE_ID;
                    db.AddToproduct_in_stock(pis);
                }
                _db.SaveChanges();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        public static bool addNewProductInfo(string barcode, string name)
        {
            _db = new dbEntities();
            try
            {
                if (_db.products_info.Count(c => c.product_code == barcode) == 0)
                {
                    products_info pdInfo = products_info.Createproducts_info(0, barcode, name);
                    db.AddToproducts_info(pdInfo);
                    db.SaveChanges();
                }
            }
            catch (Exception)
            {
                return false;
            }
            GlobalVariables.ADDED_PRODUCTS = true;
            return true;
        }

        public static bool addNewProductOnSale(string bcode, float saleprice)
        {
            if (saleprice < 0.0) return false;
            _db = new dbEntities();
            try
            {
                int pid = _db.products_info.Where(c => c.product_code == bcode).Select(c => c.product_id).First();
                product_onsale pdOS = new product_onsale();
                pdOS.product_id = pid;
                pdOS.store_id = GlobalVariables.STORE_ID;
                pdOS.sale_prices = saleprice;
                pdOS.discount = 100;
                db.AddToproduct_onsale(pdOS);
                db.SaveChanges();
            }
            catch (Exception)
            {

                return false;
            }
            return true;
        }
        #endregion
    }
    
}
